package com.afd.ozblip.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.afd.ozblip.adapter.CouponListAdapter;
import com.afd.ozblip.entity.BusinessEntity;
import com.afd.ozblip.entity.CategoryEntity;
import com.afd.ozblip.entity.CouponEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.CollectionUtil;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.OzblipConfig;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.view.UIPullRefereshListView;
import com.afd.ozblip.view.UIPullRefereshListView.OnFooterLoadListener;
import com.afd.ozblip.view.UIPullRefereshListView.OnRefreshListener;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class NearbyCouponActivity extends BaseActivity {

	/****************** 视图变量 **************************/
	private UIPullRefereshListView couponListView;
	private LinearLayout nodataLayout;
	// 条件选择视图
	private LinearLayout distanceFilterLayout;
	private LinearLayout conDistanceLayout;
	private LinearLayout categoryFilterLayout;
	private RadioGroup categoryFilterLeftLayout;
	private FrameLayout categoryFilterRightLayout;
	private LinearLayout conCategoryLayout;
	private TextView distanceTv;
	private TextView categoryTv;
	protected Animation animPushTopIn;
	protected Animation animPushTopOut;
	private RadioGroup distanceRb;
	private TextView tip3Tv;
	/****************** 数据条件变量 ***********************/
	// 父级类型名称
	private String parentClassName;
	// 子级类型名称
	private String childClassName;
	// 距离
	private int rangeVal = 5000;
	/****************** 其它变量 **************************/
	private List<CouponEntity> couponList;
	private CouponListAdapter couponListAdapter;
	// 当前页码
	private int nowPage = 1;
	// 总页数
	private int totalPage;
	// 总分类长度
	private int classLen;
	private int parentClassIndex;
	private List<CategoryEntity> categoryList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.nearby_coupon);
		// 启动返回功能
		toBack();
		// 寻找视图
		findViews();
		// 设置监听
		setListeners();
		// 获取参数
		getBundle();
		// 初始化分类
		initCategory();
		// 获取列表数据
		this.couponListView.referesh();

	}

	/**
	 * 寻找视图
	 */
	public void findViews() {
		this.couponListView = (UIPullRefereshListView) findViewById(R.id.lv_coupon_nearby);
		this.nodataLayout = (LinearLayout) findViewById(R.id.ll_coupon_nodata);
		this.tip3Tv = (TextView) findViewById(R.id.tv_coupon_tip3);
		// 条件选择视图
		this.distanceTv = (TextView) findViewById(R.id.tv_conditon_distance);
		this.categoryTv = (TextView) findViewById(R.id.tv_conditon_category);
		this.distanceFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_distance);
		this.conDistanceLayout = (LinearLayout) findViewById(R.id.ll_conditon_distance);
		this.categoryFilterLayout = (LinearLayout) findViewById(R.id.ll_conditon_filter_category);
		this.conCategoryLayout = (LinearLayout) findViewById(R.id.ll_conditon_category);
		this.animPushTopIn = AnimationUtils.loadAnimation(this,
				R.anim.push_top_in);
		this.animPushTopOut = AnimationUtils.loadAnimation(this,
				R.anim.push_top_out);
		this.distanceRb = (RadioGroup) findViewById(R.id.rg_condition_distance);
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {

		View.OnClickListener nearbyCouponClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_conditon_distance:
					categoryFilterLayout.setVisibility(8);
					conDistanceLayout.setBackgroundColor(getResources()
							.getColor(R.color.condition_select_bg));
					conCategoryLayout.setBackgroundColor(getResources()
							.getColor(R.color.transparent));
					if (distanceFilterLayout.getVisibility() == 8) {
						showFilter(distanceFilterLayout);
					} else {
						hideFilter(distanceFilterLayout);
					}
					break;
				case R.id.ll_conditon_category:
					distanceFilterLayout.setVisibility(8);
					conDistanceLayout.setBackgroundColor(getResources()
							.getColor(R.color.transparent));
					conCategoryLayout.setBackgroundColor(getResources()
							.getColor(R.color.condition_select_bg));
					if (categoryFilterLayout.getVisibility() == 8) {
						showFilter(categoryFilterLayout);
					} else {
						hideFilter(categoryFilterLayout);
					}
					break;
				default:
					break;
				}
			}
		};
		this.conDistanceLayout.setOnClickListener(nearbyCouponClick);
		this.conCategoryLayout.setOnClickListener(nearbyCouponClick);
		this.couponListAdapter = new CouponListAdapter(
				NearbyCouponActivity.this);
		this.couponList = new ArrayList<CouponEntity>();
		this.couponListAdapter.addItems(couponList);
		this.couponListView.setAdapter(this.couponListAdapter);
		this.couponListView.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				nodataLayout.setVisibility(8);
				nowPage = 1;
				requestTopListData(true);
			}
		});
		this.couponListView.setOnFooterLoadListener(new OnFooterLoadListener() {

			@Override
			public void onLoad() {
				if (nowPage < totalPage) {
					requestTopListData(false);
					nowPage = nowPage + 1;
					couponListView.nowPage = nowPage;
				}
			}
		});
		this.couponListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> itemView, View arg1,
					int parameInt, long arg3) {
				Intent businessIntent = new Intent(NearbyCouponActivity.this,
						CouponDetailActivity.class);
				CouponEntity coupon = NearbyCouponActivity.this.couponList
						.get(parameInt - 1);
				businessIntent.putExtra("coupon", coupon);
				startActivity(businessIntent);
			}
		});
		// TODO 距离选择事件
		this.distanceRb
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						switch (checkedId) {
						case R.id.rb_condition_distance500:
							distanceTv.setText("500米");
							rangeVal = 500;
							break;
						case R.id.rb_condition_distance1:
							distanceTv.setText("1千米");
							rangeVal = 1000;
							break;
						case R.id.rb_condition_distance2:
							distanceTv.setText("2千米");
							rangeVal = 2000;
							break;
						case R.id.rb_condition_distance5:
							distanceTv.setText("5千米");
							rangeVal = 5000;
							break;
						case R.id.rb_condition_distance10:
							distanceTv.setText("全城");
							rangeVal = 1000000000;
							break;

						default:
							break;
						}
						conDistanceLayout.setBackgroundColor(getResources()
								.getColor(R.color.transparent));
						if (distanceFilterLayout.getVisibility() == 8) {
							showFilter(distanceFilterLayout);
						} else {
							hideFilter(distanceFilterLayout);
						}
						couponListView.referesh();
					}
				});
	}

	private void showFilter(LinearLayout layout) {
		layout.setVisibility(0);
		layout.startAnimation(this.animPushTopIn);
	}

	private void hideFilter(LinearLayout layout) {
		layout.startAnimation(this.animPushTopOut);
		layout.setVisibility(8);
	}

	/**
	 * 获取传递的参数
	 */
	private void getBundle() {
		Intent intent = getIntent();
	}

	// TODO 初始化分类
	private void initCategory() {
		this.categoryFilterLeftLayout = (RadioGroup) findViewById(R.id.ll_conditon_filter_category_left);
		this.categoryFilterRightLayout = (FrameLayout) findViewById(R.id.ll_conditon_filter_category_right);

		LayoutInflater inflater = LayoutInflater.from(this);
		categoryList = Constants.getCategoryList();
		classLen = categoryList.size();
		View.OnClickListener leftClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int index = Integer.parseInt(v.getTag().toString());
				parentClassIndex = index;
				for (int i = 0, len = classLen; i < len; i++) {
					categoryFilterRightLayout.getChildAt(i).setVisibility(8);
				}
				categoryFilterRightLayout.getChildAt(index).setVisibility(0);
			}
		};
		View.OnClickListener rightClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				int index = Integer.parseInt(v.getTag().toString());
				parentClassName = categoryList.get(parentClassIndex)
						.getParentClassName();
				childClassName = categoryList.get(parentClassIndex)
						.getChildClassList().get(index);
				conDistanceLayout.setBackgroundColor(getResources().getColor(
						R.color.transparent));
				if (categoryFilterLayout.getVisibility() == 8) {
					showFilter(categoryFilterLayout);
				} else {
					hideFilter(categoryFilterLayout);
				}
				categoryTv.setText(childClassName);
				couponListView.referesh();
			}
		};
		for (int i = 0, len = categoryList.size(); i < len; i++) {
			View leftView = inflater.inflate(R.layout.category_left_item, null);
			RadioButton leftRB = (RadioButton) leftView;
			String parentCN = categoryList.get(i).getParentClassName();
			leftRB.setText(parentCN);
			leftRB.setId(i);
			if ("热门分类".equals(parentCN)) {
				leftRB.setChecked(true);
			}
			// 设置drawableleft
			BitmapDrawable leftbd = getListIco(i);
			leftRB.setCompoundDrawablesWithIntrinsicBounds(leftbd, null, null,
					null);
			// 设置tag
			leftRB.setTag(i);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			leftView.setOnClickListener(leftClick);
			this.categoryFilterLeftLayout.addView(leftView, lp);
			LinearLayout ll = new LinearLayout(this);
			ll.setLayoutParams(new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT));
			ll.setOrientation(LinearLayout.VERTICAL);
			ll.setVisibility(i == 0 ? 0 : 8);
			List<String> childClassList = categoryList.get(i)
					.getChildClassList();
			for (int j = 0, childLen = childClassList.size(); j < childLen; j++) {
				View rightView = inflater.inflate(R.layout.category_right_item,
						null);
				rightView.setBackgroundResource(R.drawable.ll_bg_selector);
				rightView.setTag(j);
				rightView.setOnClickListener(rightClick);
				TextView rightTv = (TextView) rightView
						.findViewById(R.id.tv_category_right);
				rightTv.setText(childClassList.get(j));

				ll.addView(rightView, lp);
			}
			this.categoryFilterRightLayout.addView(ll);
		}
	}

	private BitmapDrawable getListIco(int index) {
		Resources res = getResources();
		BitmapDrawable bd = null;
		Bitmap bm = null;
		switch (index) {
		case 0:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico1);
			bd = new BitmapDrawable(res, bm);
			break;
		case 1:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico2);
			bd = new BitmapDrawable(bm);
			break;
		case 2:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico3);
			bd = new BitmapDrawable(bm);
			break;
		case 3:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico4);
			bd = new BitmapDrawable(bm);
			break;
		case 4:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico5);
			bd = new BitmapDrawable(bm);
			break;
		case 5:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico6);
			bd = new BitmapDrawable(bm);
			break;
		case 6:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico7);
			bd = new BitmapDrawable(bm);
			break;
		case 7:
			bm = BitmapFactory.decodeResource(res, R.drawable.list_ico8);
			bd = new BitmapDrawable(bm);
			break;

		default:
			break;
		}
		return bd;
	}

	/**
	 * TODO 获取附近优惠券列表数据
	 */
	private void requestTopListData(final boolean isRefresh) {

		AsyncLoadData ald = new AsyncLoadData(this, "", new AsyncAction() {

			@Override
			public void doLoad() throws Exception {
				// 获取提交参数
				Map<String, Object> nearbyVipParamMap = new HashMap<String, Object>();
				// nearbyVipParamMap.put("area", "江北区");
				nearbyVipParamMap.put("sellerScope", rangeVal);
				nearbyVipParamMap.put("userLongitude", "29.57");
				nearbyVipParamMap.put("userDimension", "106.52");
				nearbyVipParamMap.put("pageCnt", nowPage);
				nearbyVipParamMap.put("pageRow", OzblipConfig.seller_pageSize);
				nearbyVipParamMap.put("sort", "1");
				nearbyVipParamMap.put("language", "1");
				// 发送请求
				byte[] bCouponList = HttpUtil.requestByPost(
						NearbyCouponActivity.this,
						Constants.SELLER_COUPON_LIST_API, nearbyVipParamMap);
				if (bCouponList != null) {
					couponList = new ParseJson()
							.parseBusinessCouponListJson(bCouponList);
				}
			}

			@Override
			public void loadEnd() throws Exception {
				if (couponList != null && couponList.size() == 0) {
					couponListView.onRefreshComplete();
					couponListAdapter.removeAllItem();
					couponListAdapter.notifyDataSetChanged();
					nodataLayout.setVisibility(0);
					if (!commonIsNowCity()) {
						tip3Tv.setText("如需使用附近功能，请你切换至"
								+ commonLocationCityName);
						tip3Tv.setVisibility(0);
					}else{
						tip3Tv.setVisibility(8);
					}
					return;
				}
				nodataLayout.setVisibility(8);
				if (isRefresh) {
					couponListView.onRefreshComplete();
					couponListAdapter.removeAllItem();
					couponListView.nowPage = nowPage;
					couponListView.totalPage = totalPage;
				} else {
					couponListView.loadComplete();
				}
				couponListAdapter.addItems(couponList);
				couponListAdapter.notifyDataSetChanged();
			}

		});
		ald.execute(0);
	}

	/**
	 * 调用优惠券列表适配器
	 */
	public void setCouponListAdapter() {
		if (CollectionUtil.UnNullAndZero(couponList)) {
			this.nodataLayout.setVisibility(8);
			this.couponListAdapter = new CouponListAdapter(
					NearbyCouponActivity.this);
			this.couponListAdapter.addItems(couponList);
			this.couponListView.setAdapter(this.couponListAdapter);
		} else {
			this.nodataLayout.setVisibility(0);
		}
	}

}